//
//  NSObject+Addtions.m
//  Backhome
//
//  Created by kwep_vbn on 2017/6/23.
//  Copyright © 2017年 SmartHome. All rights reserved.
//

#import "NSObject+KNAddtions.h"
#import "objc/runtime.h"


@implementation NSObject (KNAddtions)

- (NSTimer *)KNTimer {
    return objc_getAssociatedObject(self, @selector(KNTimer));
}

- (void)setKNTimer:(NSTimer *)KNTimer {
    objc_setAssociatedObject(self, @selector(KNTimer), KNTimer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)setKNRepeatAction:(RepeatCallbackType)KNRepeatAction {
    objc_setAssociatedObject(self, @selector(KNRepeatAction), KNRepeatAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (RepeatCallbackType)KNRepeatAction {
    return objc_getAssociatedObject(self, @selector(KNRepeatAction));
}

- (void)KNRepeatActionWithTimeInterval:(NSTimeInterval)interval callbackAction:(RepeatCallbackType)callback {
    self.KNRepeatAction = callback;
    [self startRepeat:interval];
}

- (void)startRepeat:(NSTimeInterval)interval {
    if (self.KNTimer) {
        [self KNCancelRepeat];
    }
    // 创建
    self.KNTimer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                    target:self
                                                selector:@selector(repeat:)
                                                  userInfo:nil
                                                   repeats:YES];
}

- (void)repeat:(id)sender {
    self.KNRepeatAction?self.KNRepeatAction():nil;
}

- (void)KNCancelRepeat {
    if (self.KNTimer) {
        [self.KNTimer invalidate];
        self.KNTimer = nil;
    }
}

@end
